package com.dhy.util;

import com.dhy.domain.RabbitmqClient;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

import static com.dhy.constants.RabbitmqConstants.*;
import static com.rabbitmq.client.BuiltinExchangeType.DIRECT;
import static com.rabbitmq.client.BuiltinExchangeType.FANOUT;

/**
 * @author 大忽悠
 * @create 2022/5/18 19:44
 */
@Slf4j
public class RabbitmqUtil {
    private final Connection connection;

    public RabbitmqUtil(String ymlPath) throws IOException, TimeoutException {
        RabbitmqClient rabbitmqClient = initRabbitmqClient(ymlPath);
        connection= rabbitmqClient.getConnection();
        log.info("connection详细信息为: {}",connection);
        log.info("连接建立");
    }

    public RabbitmqUtil(String ymlPath,String connectionName) throws IOException, TimeoutException {
        RabbitmqClient rabbitmqClient = initRabbitmqClient(ymlPath);
        connection= rabbitmqClient.getConnection(connectionName);
        log.info("连接建立,客户端设置的连接名为{}",connectionName);
    }

    public Channel createChannel() throws IOException {
        log.info("通道创建中...");
       return connection.createChannel();
    }

    public Channel prepareChannel() throws IOException, TimeoutException {
        RabbitmqUtil rabbitmqUtil = new RabbitmqUtil("application.yml","dhy-connection");
        Channel channel = rabbitmqUtil.createChannel();
        //声明交换机和队列
        //非持久化、非自动删除的“扇形”形交换机
        channel.exchangeDeclare(EXCHANGE_NAME, FANOUT, false);
        //拥有既定名称的，非持久化、非独占、非自动删除的队列
        channel.queueDeclare(TEMP_QUEUE, false, false, false, null);
        //绑定交换机和队列
        channel.queueBind(TEMP_QUEUE, EXCHANGE_NAME, ROUTING_KEY);
        log.info("准备channel中..");
        return channel;
    }

    public void close(){
        log.info("关闭rabbitmq连接中...");
        try {
            //channel.close(); 非必须
            connection.close();
        } catch (IOException e) {
            log.error("关闭连接过程中出现错误: ",e);
        }
    }

    private RabbitmqClient initRabbitmqClient(String ymlPath) {
        YamlUtil yamlUtil = new YamlUtil(ymlPath);
        String keyPrefix = "spring.rabbitmq.";
        RabbitmqClient rabbitmqClient = RabbitmqClient.builder()
                .userName(yamlUtil.get(keyPrefix + "username"))
                .password(yamlUtil.get(keyPrefix + "password"))
                .host(yamlUtil.get(keyPrefix + "host"))
                .port(Integer.valueOf(yamlUtil.get(keyPrefix + "port")))
                .virtualHost(yamlUtil.get(keyPrefix + "virtual-host"))
                .build();
        return rabbitmqClient;
    }

    public Connection getConnection(){
        return connection;
    }

}
